<?php
/**
 *
 * @param $big_name
 * @param $big_file
 * @param $big_ext
 * @param $dim_big
 * @param $extensions
 * @param $small
 * @param $small_name
 * @param $small_file
 * @return unknown_type
 */
function file_upl($big_name, $big_file, $big_ext, $dim_big = '', $extensions = '', $small = 0, $small_name = '', $small_file = ''){
	//TODO check dimension of big file if its allowed
	$r = 0;
	//check if file size is bigger then 0
	if ($big_file['size'] > 0) {
		//check if file extension is accaptable
		if (is_array($extensions)) {
			if (!in_array($big_ext, $extensions)) {
				if (FW_DEBUG == 1) {
					print('Extention of file which you send is inpropriate.<br />');
				}
				return 0;
			}
		}
		move_uploaded_file($big_file['tmp_name'], $big_name);
		chmod($big_name, FILE_CHMOD);
		if (file_exists($big_name)) $r = 1;
		if (FW_DEBUG == 1) {
			if ($r == 1) {
				//print('File uploaded.<br />');
			} else {
				print('Problem with file upload.<br />');
			}
		}
	} else {
		return 0;
	}
	//check if small file was uploaded
	if ($small == 1) {
		if ($small_file['size'] > 0) {
			$r = 0;
			move_uploaded_file($small_file['tmp_name'], $small_name);
			chmod($small_name, FILE_CHMOD);
			if (file_exists($small_name)) {
				$r = 1;
			}
			if (FW_DEBUG == 1) {
				if ($r == 1) {
					print('Thumbnail added.<br />');
				} else {
					print('Problem with thumbnail.<br />');
				}
			}
		}
	}
	return $r;
}

##################################
#form fields functions
##################################
function array_norm($array, $value){
	$r = '';
	foreach ($array as $vl) {
		$r .= '<option';
		if ($vl == $value) {
			$r .= ' selected';
		}
		$r .= '>'.$vl.'</option>';
	}
	return $r;
}

function array_assoc($array, $value){
	$r = '';
	foreach ($array as $ky => $vl) {
		$r .= '<option value="'.$ky.'"';
		if ($ky == $value) {
			$r .= ' selected';
		}
		$r .= '>'.$vl.'</option>';
	}
	return $r;
}

function massoc_opt($array, $value){
	$r = '';
	if (is_array($value)) {
		$typ = 1;
	} else {
		$typ = 2;
	}
	foreach ($array as $ky => $vl) {
		$r .= '<option value="'.$ky.'"';
		if ($typ == 1) {
			if (in_array($ky, $value)) {
				$r .= ' selected';
			}
		} else {
			if ($ky == $value) {
				$r .= ' selected';
			}
		}
		$r .= '>'.$vl.'</option>';
	}
	return $r;
}

function radio_list($name,$array,$value,$spacer='<br />'){
	$r = '';
	foreach ($array as $ky => $vl) {
		$r .= '<label><input type="radio" name="'.$name.'" value="'.$ky.'"';
		if ($ky == $value) $r .= ' checked="checked"';
		$r .= ' /> '.$vl.$spacer.'</label>';
	}
	return $r;
}

function checkbox_assoc($name,$array,$value,$spacer='<br />'){
	$r = '';
	foreach ($array as $ky => $vl) {
		$field_id = 'field_'.$ky;
		$r .= '<label><input type="checkbox" id="'.$field_id.'" name="'.$name.'" value="'.$ky.'"';
		if ($ky == $value) $r .= ' checked="checked"';
		$r .= '> '.$vl.$spacer.'</label>';
	}
	return $r;
}

function sqlGetKey($rsl){
	global $db;
	$row = FetchField(0);
	return $row['name'];
}

//TODO redo that function
//should work for ... Assoc, Normal array
//query, array
function getArray($inf,$gType=''){
	if (!$inf) return;
	global $db;
	$aType = 'X';
	$iType = gettype($inf);
	if (is_array($inf)) return $inf;
	elseif ($iType == 'resource' || preg_match ('!SELECT(.*)FROM!Uis', $inf)) {
		if ($iType != 'resource') {
			$rsl = $db->Execute($inf);
			$cols = substr_count($inf, ',')+1;
			if ($gType == 'A') $ky = sqlGetKey($rsl);
		} else {
			$rsl = $inf;
			$ky = sqlGetKey($rsl);
		}
		$inf = array();
		if ($gType == 'A') {
			while($row=$rsl->FetchRow()) {
				$vl = $row[$ky];
				$aType = 'A';
				array_shift($row);
				$inf[$vl] = $row;
			}
		} else {
			while($row=mysql_fetch_row($rsl)) {
				if (!isset($type)) {
					if ($cols == 2) {
						$type = 2;
						$aType = 'A';
					}else $aType = 'N';
				}
				if ($type == 2) $inf[$row[0]] = $row[1];
				else $inf[] = $row[0];
			}
		}
	} else {
		$inf = explode("\n", $inf);
		$aType = 'N';
	}
	$r = array($inf,$aType);
	return $r;
}

function prepare_number($value,$param){
	$value = str_replace(',', '.',$value);
	$pos = strpos($param['param1'], '.');
	if ($pos>0) {
		$param['type'] = 'F';
		$expl = explode('.', $param['param1']);
	} else {
		$expl[1] = 0;
	}
	return array(round($value, $expl[1]),$param);
}

function fw_paged_results_js($head, $entity, $all, $link, $limit = 10, $replace = 'div#listing_result', $add_name = '', $add_link_vl = ''){
	if ($_REQUEST[$entity]['limit']) {
		$limit = $_REQUEST[$entity]['limit'];
	}
	if ($all == 0) {
		return '';
	}
	if ($limit > 0) {
		$r = '';
		$p = $_REQUEST[$entity]['page'];
		$pages = ceil($all/$limit);
		if (!$p) {
			$p = 0;
			$p_replace = 0 ;
		} else {
			$p_replace = $_REQUEST[$entity]['page'];
		}
		if (!strstr($link,'&'.$entity.'[page]='.$p_replace)) {
			$link .= '&'.$entity.'[page]='.$p_replace;
		}
		$r .= '<div class="fw-pages">';//.$head;
		if ($pages > 1) {
			if (($p_replace - 1) > -1) {
				$link_show = str_replace($entity.'[page]='.$p_replace, $entity.'[page]='.($p_replace - 1), $link);
				$r .= ' <a href="#p0" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')" style="padding: 0 5px;">&lt;</a> ';
			} else {
				$r .= ' <span style="padding: 0 5px;">&lt;</span> ';
			}
			
			if (($p_replace + 1) < $pages) {
				$link_show = str_replace($entity.'[page]='.$p_replace, $entity.'[page]='.($p_replace + 1), $link);
				$r .= ' <a href="#p0" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')" style="padding: 0 5px;">&gt;</a> ';
			} else {
				$r .= ' <span style="padding: 0 5px;">&gt;</span> ';
			}
			
			if ($add_name) {
				if ($add_link_vl != '') {
					$add_link_vl = '&amp;'.$add_link_vl;
				}
				if ($p == $add_link_vl) {
					$r .= '<span class="active ui-state-default" style="padding: 0 5px;">'.$add_name.'</span> ';
				} else {
					$r .= '<a href="'.$link.$add_link_vl.'" style="padding: 0 5px;">'.$add_name.'</a> | ';
				}
			}
			$p += 1;
			$llimit = 1;
			if ($p == 0) {
				$from = 0;
				$to = $llimit;
			} else {
				$from = $p-$llimit;
				$to = $p+$llimit;
			}
			if ($to > $pages) {
				$from += $pages-$to;
				$to = $pages;
			}
			--$from;
			if ($from < 1) {
				$to = $llimit*3;
				$from = 0;
			}
			if ($to > $pages) {
				$to = $pages;
			}
			
			if ($from > 0) {
				$link_show = str_replace($entity.'[page]='.$p_replace, $entity.'[page]=0', $link);
				$r .= '<a href="#p0" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')" style="padding: 0 5px;">1</a> ';
				if ($from > 1) {
					$r .= '<span style="padding: 0 5px;"> .. </span> ';
				}
			}
			for($i=$from; $i<$to; $i++) {
				$link_show = str_replace($entity.'[page]='.$p_replace,$entity.'[page]='.$i,$link);
				if ($i != $p-1) {
					$r .= '<a href="#p'.($i).'" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')" style="padding: 0 5px;">'.($i+1).'</a>';
				} else {
					$r .= '<span class="active ui-state-default" style="padding: 0 5px;">'.($i+1).'</span>';
				}
			}

			if ($to+1 < $pages) {
				$r .= ' <span style="padding: 0 5px;"> .. </span> ';
			}
			$link_show = str_replace($entity.'[page]='.$p_replace,$entity.'[page]='.($pages-1),$link);

			if ($to < $pages) {
				$r .= '<a href="#p'.($pages-1).'" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')" style="padding: 0 5px;">'.$pages.'</a>';
			}
		} else {
			$r .= '<span style="padding: 0 5px;">&lt;</span> <span style="padding: 0 5px;">&gt;</span><span style="padding: 0 5px;" class="active ui-state-default">1</span>';
		}
		$r .= '</div>';
		return $r;
	}
}

function fw_paged_results_js2($head, $entity, $all, $link, $limit = 10, $replace = 'div#listing_result', $add_name = '', $add_link_vl = ''){
	if ($_REQUEST[$entity]['limit']) {
		$limit = $_REQUEST[$entity]['limit'];
	}
	if ($limit > 0) {
		$r = '';
		$p = $_REQUEST[$entity]['page'];
		$pages = ceil($all/$limit);
		if (!$p) {
			$p = 0;
			$p_replace = 0 ;
		} else {
			$p_replace = $_REQUEST[$entity]['page'];
		}
		if (!strstr($link,'&'.$entity.'[page]='.$p_replace)) {
			$link .= '&'.$entity.'[page]='.$p_replace;
		}
		if ($pages > 1) {
			$r .= '<div class="fw-pages">';//.$head;
			if (($p_replace - 1) > -1) {
				$link_show = str_replace($entity.'[page]='.$p_replace, $entity.'[page]='.($p_replace - 1), $link);
				$r .= ' <a href="#p0" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')"><strong>&lt;</strong></a> ';
			} else {
				$r .= ' &lt; ';
			}
			
			if (($p_replace + 1) < $pages) {
				$link_show = str_replace($entity.'[page]='.$p_replace, $entity.'[page]='.($p_replace + 1), $link);
				$r .= ' <a href="#p0" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')"><strong>&gt;</strong></a> ';
			} else {
				$r .= ' &gt; ';
			}
			
			if ($add_name) {
				if ($add_link_vl != '') {
					$add_link_vl = '&amp;'.$add_link_vl;
				}
				if ($p == $add_link_vl) {
					$r .= '<span class="active">'.$add_name.'</span> ';
				} else {
					$r .= '<a href="'.$link.$add_link_vl.'">'.$add_name.'</a> | ';
				}
			}
			$p += 1;
			$llimit = 1;
			if ($p == 0) {
				$from = 0;
				$to = $llimit;
			} else {
				$from = $p-$llimit;
				$to = $p+$llimit;
			}
			if ($to > $pages) {
				$from += $pages-$to;
				$to = $pages;
			}
			--$from;
			if ($from < 1) {
				$to = $llimit*3;
				$from = 0;
			}
			if ($to > $pages) {
				$to = $pages;
			}
			
			if ($from > 0) {
				$link_show = str_replace($entity.'[page]='.$p_replace, $entity.'[page]=0', $link);
				$r .= '<a href="#p0" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')">1</a> ';
				if ($from > 1) {
					$r .= '<span> ... </span> ';
				}
			}
			for($i=$from; $i<$to; $i++) {
				$link_show = str_replace($entity.'[page]='.$p_replace,$entity.'[page]='.$i,$link);
				if ($i != $p-1) {
					$r .= '<a href="#p'.($i).'" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')">'.($i+1).'</a>';
				} else {
					$r .= '<span class="active">'.($i+1).'</span>';
				}
			}

			if ($to+1 < $pages) {
				$r .= ' <span> ... </span> ';
			}
			$link_show = str_replace($entity.'[page]='.$p_replace,$entity.'[page]='.($pages-1),$link);

			if ($to < $pages) {
				$r .= '<a href="#p'.($pages-1).'" onclick="load_page(\''.$replace.'\',\'index.php?'.$link_show.'&amp;ajax=1\')">'.$pages.'</a>';
			}
			$r .= '</div>';
		}
		return $r;
	}
}

/**
 * paginate listed results
 *
 * @return HTML code with list to pages
 * @param string $head header
 * @param integer $all number of records
 * @param string $link default link
 * @param integer $limit[optional] no of records per page default 10
 * @param string $add_name[optional] additional link header
 * @param string $add_link_vl[optional] additional link
 */
function fw_paged_results($head,$all,$link,$limit=10,$add_name='',$add_link_vl=''){
	$r = '';
	$p = $_REQUEST['page'];
	if (isset($_REQUEST['sort_by'])) $link .= '&amp;sort_by='.$_REQUEST['sort_by'];
	if (isset($_REQUEST['sort_order'])) $link .= '&amp;sort_order='.$_REQUEST['sort_order'];
	$pages = ceil($all/$limit);
	if (!$p) $p = 0;
	if ($pages>1) {
		$r .= '<div class="fw-pages">'.$head;
		if ($add_name) {
			if ($p == $add_link_vl) $r .= '<span class="active">'.$add_name.'</span> ';
			else $r .= '<a href="index.php?'.$link.'&amp;'.$add_link_vl.'">'.$add_name.'</a> | ';
		}
		$p += 1;
		$llimit = 5;
		if ($p == 0) {
			$from = 0;
			$to = $llimit;
		} else {
			$from = $p-$llimit;
			$to = $p+$llimit;
		}
		if ($to>$pages) {
			$from += $pages-$to;
			$to = $pages;
		}
		--$from;
		if ($from<1) {
			$to = $llimit*2;
			$from = 0;
		}
		if ($to>$pages) $to = $pages;
		if ($from>0) {
			$r .= '<a href="'.$_SERVER['PHP_SELF'].'?'.$link.'&amp;page=0">1</a> ';
			if ($from>1) $r .= '<span> ... </span> ';
		}
		for($i=$from;$i<$to;$i++) {
			if ($i != $p-1) $r .= '<a href="'.$_SERVER['PHP_SELF'].'?'.$link.'&amp;page='.$i.'">'.($i+1).'</a>';
			else $r .= '<span class="active">'.($i+1).'</span>';
		}
		if ($to+1<$pages) $r .= ' <span> ... </span> ';
		if ($to<$pages) $r .= '<a href="'.$_SERVER['PHP_SELF'].'?'.$link.'&amp;page='.($pages-1).'">'.$pages.'</a>';
		$r .= '</div>';
	}
	return $r;
}

/**
 * set number to money format
 *
 * @param $number
 * @return money format
 */
function format_money($number, $type = 1){
	global $global_config;
	if ($type == 2 && 1==2) {
		list($money, $decimal) = explode('.', $number);
		$m = number_format((double)$number, strlen($decimal), '.', ',');
	} else {
		$m = number_format((double)$number, 2, '.', ',');
	}
	
	$mx = explode('.', $m);
	if ($mx[1] == '') {
		$mx[1] == '00';
	}
	
	if ($mx[1] == '00') {
		$m = $mx[0];
		if ($global_config['system']['MONEY_FORCE_DECIMALS'] == 1) {
			$m .= '.00';
		}
	} else if (strlen($mx[1]) == 1){
		$m .= '0';
	}
	return $m;
}

/**
 * for autocomplete function
 * need fields name , table name and queryString
 * call by form_input autocomplete @ framework_fields.php
 */
function fw_lookup2(){
	global $db;
	#cleanup before checking with database
	$clean = array('c', 't', 'q');
	foreach ($clean as $k) {
		$_REQUEST[$k] = mysql_real_escape_string($_REQUEST[$k]);
	}
	$sql = 'SELECT DISTINCT(`'.$_REQUEST['c'].'`)
	FROM '.$_REQUEST['t'].'
	WHERE `'.$_REQUEST['c'].'` LIKE "'.$_REQUEST['q'].'%" ORDER BY `'.$_REQUEST['c'].'`';
	$row = $db->GetCol($sql,'fw');
	if (is_array($row)) {
		foreach ($row as $k => $v) {
			echo $v."\n";
		}
	}
}

function get_date($timestamp){
	if (strlen($timestamp) > 10) {
		return substr($timestamp,0,10);
	} else {
		return $timestamp;
	}
}

function date_fix_format($date){
	if (!ereg('([0-9]{4})-([0-9]{2})-([0-9]{2})', $date)) {
		$date_ymd_format = CALENDAR_DATE_HACK_YMD;
		preg_match(CALENDAR_DATE_HACK_PATTERN, $date, $matches_date);
		$date = $matches_date[$date_ymd_format{0}].'-'.$matches_date[$date_ymd_format{1}].'-'.$matches_date[$date_ymd_format{2}];
//		echo 're-form_date';
	}
	return $date;
}

function format_time($t, $type = 1){
	$t *= 1;
	if ($t > 0) {
		if ($type == 3) {
			return date($_SESSION[SESSION_A]['format_time'], $t);
		} else {
			if ($t > 3599) {
				$h = floor($t / 3600);
				$m = $t - $h * 3600;
				if ($h < 10) {
					$h = '0'.$h;
				}
			} else {
				$h = '00';
				$m = $t;
			}
			$m = floor($m/60);
			if ($m < 10) {
				$m = '0'.$m;
			}
			$s = ($t%60);
			if ($s < 10) {
				$s = '0'.$s;
			}
			if ($type == 2) {
				return $m.':'.$s;
			} else if ($type == 3) {
				return $h.':'.$m;
			} else {
				return $h.':'.$m.':'.$s;
			}
		}
	} else {
		if ($type == 2 || $type == 3) {
			return '00:00';
		} else {
			return '00:00:00';
		}
	}
}

/**
 * set format date
 *
 * @param date $date
 * @param int $typ
 * @return date format
 */
function format_date($d, $typ = 1){
	if (!$d || $d == '0000-00-00') {
        return;
    }
    //change into unix time
    if (!is_int($d)) {
        $d = strtotime($d);
    }
    
    if ($typ == 1) {
        return date(CALENDAR_FORMAT, $d);
    } else if ($typ == 2) {
        return date($_SESSION[SESSION_A]['format_date'], $d);
    } else if ($typ == 3) {
        $js_separate = CALENDAR_JS_SEPARATE;
        $js_format = CALENDAR_JS_FORMAT;
        return date($js_format{0}.$js_separate{0}.$js_format{1}.$js_separate{0}.$js_format{2}.$js_separate{0}, $d);
    } else if ($typ == 4) {
    	return date($_SESSION[SESSION_A]['format_date_extd'], $d);
    } else if ($typ == 5) {
    	return gain_time_status($d);
    }
}

function gain_time_status ($time) {

//	$diff = abs(strtotime('now') - $time);
//	$years   = floor($diff / (365*60*60*24));
//	$months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
//	$days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
//	$hours   = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
//	$minuts  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);

	if ($time <= strtotime('-12 months')) {
		$post_status = 'over year ago';
	} elseif (($time <= strtotime('-2 months')) && ($time > strtotime('-12 months'))) {
		$post_status = 'a few months ago';
	} elseif (($time <= strtotime('-1 month')) && ($time > strtotime('-2 months'))) {
		$post_status = 'a month ago';
	} elseif (($time <= strtotime('-14 days')) && ($time > strtotime('-1 month'))) {
		$post_status = 'a few weeks ago';
	} elseif (($time <= strtotime('-7 days')) && ($time > strtotime('-14 days'))) {
		$days = date("d") - date("d", $time);
		if($days < 0) {
			$days =	date("t", $time) - date("d", $time) + date("d") + 1;
			if ($days > 7){
				$post_status = 'a weeks ago';
			} else {
				$post_status = 'a week ago';
			}
		} else {
			$post_status = 'a week ago';
		}
	} elseif (($time <= strtotime('-2 days')) && ($time > strtotime('-7 days'))) {
		$post_status = 'a few days ago';
	} elseif ((date("d") - date("d", $time)) == 1) {
		if (date("m", $time) == date("m")) {
			$post_status = 'yesterday';
		} elseif (date("m") - date("m", $time) == 1) {
			$post_status = 'a few weeks ago';
		} else {
			$post_status = 'a few months ago';
		}
	} elseif ((date("d", $time) == date("d")) && (date("m", $time) == date("m"))) {
		if ($time > strtotime('-2 hours')) {
			$post_status = 'just now';
		} elseif (($time <= strtotime('-2 hours')) && ($time > strtotime('-24 hours'))) {
			$post_status = 'today';
		}
	} 
	return $post_status;
}

function format_date_time($date, $format = '', $typ = 1){
	if ($date == '') {
		return;
	}
	$d = strtotime($date);
	
	
	if ($format != '') {
		return date($format, $d);
	}

	if ($typ == 1) {
		return format_date($d) . ' ' . format_time($d, 3);
	} else if ($typ == 2) {
		return format_date($d) . ' ' . format_time($d, 3);
	} else if ($typ == 4) {
		return date($_SESSION[SESSION_A]['format_date_extd'], $d). ' ' . format_time($d, 3);
	}
}

function unix_into_db($time){
	if ($time > 0) {
		return '"'.date('Y-m-d H:i:s', $time).'"';
	} else {
		return 'NULL';
	}
}

/**
 * change array into CSV content
 * @param array $data array which will be changed
 * @return content of CSV file
 */
function array_into_csv($data, $column = "\t", $row = "\r\n", $tab = '//TAB', $new_line = '//NEW_LINE'){
	$r = '';
	$k = 0;
	$all = count($data);
	foreach ($data as $a => $b) {
		$l = 0;
		foreach ($b as $c => $d) {
			++$l;
			if ($l > 1) {
				$r .= $column;
			}
			if ($new_line != 'skip') {
				$d = str_replace("\n", $new_line, $d);
			}
			if ($tab != 'skip') {
				$d = str_replace("\t", $tab,$d);
			}
			$r .= $d;
		}
		if (++$k < $all) {
			$r .= $row;
		}
	}
	//$r = substr($r,0,-strlen($row));
	return $r;
}

/**
 * create csv file from array from database and zip it
 *
 * @param array $array array which suppose to be zipped
 * @param mixed $files file(s) names
 * @param string $base64 compress files so it can be safetly send
 * @return content of zipped file
 */
function file_csv_zip($array, $files, $base64 = 1){
	$zip = new zipfile();
	if (is_array($files)) {//multiple files
		foreach ($files as $file) {
			$r = array_into_csv($array[$file]);
			$zip->addFile($r, $file);
		}
	} else {//single file
		$array = array_into_csv($array);
		$zip->addFile($array, $files);
	}
	$r = $zip->file();
	if ($base64 == 1) {
		$r = base64_encode($r);
	}
	return $r;
}

/**
 * use for add array with word...
 * ==== ====
 * array_walk($primary_field, 'array_alter', 'field_');
 * return implode(' ',$primary_field);
 */
function array_alter(&$item1, $key, $prefix){
  $item1 = '{{'.$prefix.$item1.'}}';
}

/**
 *
 * @param $arr array 2D
 * @param $key key name which we sort
 * @param $style natural/numeric
 * @param $return return or assign
 * @return array
 */
function sort_array_2d(&$arr, $key, $style = 'natural', $return = false, $order = 'ASC'){
	if (is_array($arr)) {
		foreach ($arr as $k => $v) {
			$tmp_rsl[$k] = $v[$key];
		}
		if (is_array($tmp_rsl)) {
			if ($style == 'numeric') {
				arsort($tmp_rsl);
			} else {
				natcasesort($tmp_rsl);
			}

			if ($order == 'DESC') {
				$count_rsl = count($tmp_rsl);
				$pop_tmp = array_keys($tmp_rsl);
				$pop_array = array();
				for ($i=0; $i < $count_rsl; $i++) {
					$pop_key = array_pop($pop_tmp);
					$pop_array[$pop_key] = $tmp_rsl[$pop_key];
				}
				$tmp_rsl = $pop_array;
			}

			foreach ($tmp_rsl as $k => $v) {
				if (is_array($arr[$k])) {
					foreach ($arr[$k] as $kk => $vv) {
						$rsl[$k][$kk] = $vv;
					}
				}
			}
		}
		if ($return) {
			return $rsl;
		} else {
			$arr = $rsl;
		}
	}
}

/**
 * fetch list of avilable themes for template
 * @param $theme_path	string
 * @return array with list of avilable themes
 */
function gain_get_templates($theme_path = 'tpl/ui/theme/', $default = 1){
	$theme = array();
	$h = opendir($theme_path);
	while($f=readdir($h)) {
		if ($f != '.' && $f != '..' && $f != 'default' && $f != '.svn' && is_dir($theme_path.$f)) {
			$theme[$theme_path.$f.'/'] = str_replace('-', ' ', $f);
		}
	}
	asort($theme);
	$theme_default = array($theme_path.'default/' => msg('default_theme'));
	if($default == 1) {
		return $theme_default+$theme;
	} else {
		return $theme;
	}
}

/**
 * validate date
 * accept date or date & time
 * @param $date
 * @return boolean
 */
function gain_date_validate($date){
	if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
		return false;
	} else {
		return true;
	}
}

function gain_log_set($entity, $stringData, $action = ''){
	global $db;
	return;
	$path_name = PATH."files/temp/log/";
	if (!is_dir($path_name)) {
		mkdir($pathname);
	}
	$myFile = $path_name."log_".$entity."_".date('Y-m-d').".txt";

	if ($fh = fopen($myFile, 'a+')) {
		$stringData = date('Y-m-d H:i:s')."(".$_SESSION[SESSION_N]."): \n".$action."\n\r".$stringData."\n\r---------------------------------------------------\n\r";
		chmod($myFile, 0777);
		fwrite($fh, $stringData);
		fclose($fh);
	} else {
		die("can't open file");
	}
}

function gain_log_get($entity, $sql, $date){
	global $db;
}

function format_number_scale ($number, $specific = 'A') {
	$scale = '';
	$negative_flag = false;

	if ($number < 0) {
		$negative_flag = true;
		$number =  $number * (-1);
	}
	if ( ($number >= 1000000 && $specific == 'A') || $specific == 'M' ) {
		$scale = format_money( (round($number/10000))/100 ).'M';
	} else if ( ($number >= 1000 && $specific == 'A') || $specific == 'K' ) {
		$scale = format_money( (round($number/10))/100 ).'K';
	} else {
		$scale = format_money($number);
	}

	if ($negative_flag) {
		$scale = '-'.scale;
	}
	
	return $scale;
}
?>